<template>
	<view class="">
		<!-- 企业头部 -->
		<view class="bg-white p-2" v-if="headShow"><company-header v-if="companyUser" :company-user="companyUser" :isIcon="false" @userChange="userChange"></company-header></view>
		<!-- 产品头部 -->
		<view class="mt-4" v-else><product-list :list="proHead" :btn-show="false" :exhibition-id="exhibitionId" class="flex flex-wrap justify-between"></product-list></view>
		<view class="bg-white" style="margin-top: -20rpx;">
			<scroll-view scroll-y="true" :style="headShow ? 'height:90vh' : 'max-height: 300rpx;'">
				<view v-if="list.length <= 0" class="p-2" style="margin:auto;">
					<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" text="暂无资料" width="60" height="60"></u-empty>
				</view>
				<view v-else class="mt-2 bg-white p-2 w-100">
					<view class="mb-2" v-for="(item, index) of list" :key="item.id">
						<view class="flex justify-between">
							<view class="flex tit" @tap="openLook(item, index)">
								<view class="imgicon"><image :src="item.file_type_img" mode="aspectFit" class="imgicon"></image></view>
								<text class="tit h6 ml-1">{{ item.title + '.' + item.file_type }}</text>
							</view>
							<view class="ml-2">
								<!-- 已下载 -->
								<view v-if="item.route_url"><image src="@/static/img2/my/finish.png" mode="aspectFit" style="width: 50rpx;height: 50rpx;"></image></view>
								<!-- 未下载 -->
								<view @tap="downLoad(item, index)" v-else><u-icon name="download" color="#CF1526" size="28"></u-icon></view>
								<!-- 文件下载进度条 -->
								<u-popup :show="item.rateState" @close="item.rateState = false" mode="center">
									<view class="py-3 px-5" v-if="item.rateState">
										<view class="text">文件下载中，请稍后......</view>
										<progress :percent="item.progress" show-info stroke-width="3" />
									</view>
								</u-popup>
							</view>
						</view>
						<!-- MP4/MP3查看 -->
						<u-popup :show="item.fileShow" @close="closePopup(item, index)" mode="center">
							<video v-if="item.file_type == 'mp4'" :src="item.img_url"></video>
							<audio v-else :src="item.img_url"></audio>
						</u-popup>
					</view>
					<!-- <u-loadmore :status="status" color="#E5E5E5" lineColor="#E5E5E5" dashed line /> -->
				</view>
			</scroll-view>
		</view>
		<view class="mt-2"><product-center v-if="downUid" down-pro="downPro" :down-uid="downUid" :down-exhibitionId="exhibitionId"></product-center></view>

		<!-- 下载成功弹框 -->
		<u-popup :show="overShow" @close="overShow = false" mode="center" :closeable="true">
			<view class="over_box">
				<image src="@/static/img2/home/download_over.jpg" mode=""></image>
				<view class="top_text text-center">
					<view class="font-md text-white">下载成功！</view>
					<view class="font-md text-white">请前往个人中心查看</view>
				</view>
				<view class="over_cont top_text">
					<view class="middle_text text-center">
						<view class="c_main font-lg font-weight-bold ">邀请您：</view>
						<view class="font mt-2">快速结束SNEC现场通讯录</view>
						<view class="font mt-1">结识更多朋友</view>
					</view>
					<view class="bot_btn text-center mt-4">
						<button class="font-md bg_main text-white" @click="toCardlist">前往现场通讯录</button>
						<view class="font mt-2 c_9" @click="goTab('/pages/my/index')">个人中心</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { filesList, filesDownload, filesProductTop, fileRoute } from '@/api/my/uploadfile.js';
import { filesProduct } from '@/api/home/nav/product_data.js';
import companyHeader from './header.vue';
import productList from '@/components/product_list/product_list.vue';
import { baseUrl } from '@/util/api.js';
import productCenter from '@/subPages/company_home/product_center.vue';
export default {
	components: {
		companyHeader,
		productList,
		productCenter
	},
	data() {
		return {
			overShow: false,
			list: [],
			companyUser: null,
			page: 1, //页数
			suo: true,
			status: 'loadmore',
			fileStorage: [],
			islook: false,
			headShow: false,
			exhibitionId: '',
			// 产品
			proId: '',
			proStatus: '',
			title: '',
			proHead: [],
			downUid: ''
		};
	},
	onLoad(option) {
		// console.log('==', option);
		this.exhibitionId = option.exhibitionId;
		if (option.id) {
			this.headShow = false;
			this.proId = option.id;
			this.proStatus = option.c_status;
			console.log('==', this.proStatus);
			this.title = option.title;
			this.getProductHead();
		} else {
			this.companyUser = JSON.parse(decodeURIComponent(option.companyUser));
			this.headShow = true;
		}
		this.getList();
		// console.log(uni.getStorageSync('fileId'));
		// this.fileStorage = uni.getStorageSync('fileId') || [];
		// 分享
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
	},
	onReachBottom() {
		if (this.suo) {
			//定义个小锁，当没有数据时锁住suo
			this.status = 'loading';
			this.page = ++this.page;
			setTimeout(() => {
				this.getList();
			}, 1000);
		}
		uni.$emit('onReachBottomDownload');
	},
	methods: {
		userChange(val) {
			// console.log('下载页面', val);
			this.companyUser = val;
		},
		getList() {
			if (this.proId) {
				// 产品文件列表
				let msg = {
					id: this.proId,
					c_status: this.proStatus,
					page: this.page
				};
				filesProduct(msg).then(res => {
					if (res.code == 0) {
						this.list.push(...res.data);
						if (res.data.length == 0) {
							this.status = 'nomore';
							this.suo = false;
						} else if (res.data.length < 10) {
							this.status = 'nomore';
							this.suo = false;
						} else {
							this.status = 'loadmore';
							this.suo = true;
						}
					} else {
						uni.$u.toast(res.msg);
					}
				});
			} else {
				// 企业文件列表
				let msg = {
					uid: this.companyUser.id,
					page: this.page
				};
				filesList(msg).then(res => {
					if (res.code == 0) {
						this.list.push(...res.data);
						if (res.data.length == 0) {
							this.status = 'nomore';
							this.suo = false;
						} else if (res.data.length < 10) {
							this.status = 'nomore';
							this.suo = false;
						} else {
							this.status = 'loadmore';
							this.suo = true;
						}
					} else {
						uni.$u.toast(res.msg);
					}
				});
			}
		},
		// 获取产品头部数据
		getProductHead() {
			filesProductTop({
				id: this.proId,
				c_status: this.proStatus
			}).then(res => {
				this.proHead = [res.data];
				this.downUid = res.data.uid;
			});
		},
		async downLoad(val, idx) {
			let that = this;
			uni.showModal({
				// title: '提示',
				content: '确定下载吗?',
				confirmColor: '#E30012',
				success: res => {
					if (res.confirm) {
						console.log('==111', that.proStatus);
						//0:企业 1:参数型产品 2:图文型产品
						let type = that.proId ? parseInt(that.proStatus) + 1 : 0;
						let msg = {
							id: val.id,
							type: type,
							zhanhui_id: that.exhibitionId,
							title: that.proId ? that.title : that.companyUser.business_company,
							relevance_id: that.proId ? that.proId : that.companyUser.id
						};
						// 下载验证
						filesDownload(msg).then(timeRes => {
							// console.log('接口', timeRes);
							if (timeRes.code == 0) {
								// uni.showLoading({ title: '正在下载……' });
								const uploadTask = uni.downloadFile({
									url: val.img_url, //下载地址接口返回
									success: data => {
										// console.log('下载', data);
										if (data.statusCode === 200) {
											//隐藏加载框
											// uni.hideLoading();
											//文件保存到本地
											uni.saveFile({
												tempFilePath: data.tempFilePath, //临时路径
												success: saveRes => {
													// console.log('保存文件到本地', saveRes);
													//自动打开文档查看
													// setTimeout(() => {
													var filePath = saveRes.savedFilePath;
													// console.log('打开文档', filePath);
													fileRoute({ id: timeRes.id, route_url: filePath }).then(res => {
														console.log('保存路径', res);
													});
													that.$set(that.list[idx], 'route_url', filePath);
												},
												fail: saveErr => {
													console.log('保存错误', saveErr);
												}
											});
										} else {
											uni.$u.toast('下载失败');
											that.$set(that.list[idx], 'rateState', false);
											// that.$set(that.list[idx], 'progress', 100);
										}
									},
									fail: err => {
										console.log('下载失败', err);
										uni.showToast({
											icon: 'none',
											mask: true,
											title: '文件下载失败'
										});
										that.$set(that.list[idx], 'rateState', false);
										// that.$set(that.list[idx], 'progress', 100);
									}
								});
								uploadTask.onProgressUpdate(res => {
									// console.log('上传进度' + res.progress);
									that.$set(that.list[idx], 'progress', res.progress);
									if (res.progress > 0) {
										// that.rateState = true;
										that.$set(that.list[idx], 'rateState', true);
									}
									if (res.progress >= 95) {
										setTimeout(() => {
											that.$set(that.list[idx], 'rateState', false);
											uni.$u.toast('下载成功');
											// that.overShow = true;
											// uni.showToast({
											// 	icon: 'success',
											// 	mask: true,
											// 	title: '下载成功，请前往 个人中心-我的下载 查看~',
											// 	duration: 2000
											// });
										}, 2000);
									}
								});
							} else {
								console.log('下载失败', timeRes.msg);
								uni.$u.toast(timeRes.msg);
								that.$set(that.list[idx], 'route_url', '');
								that.$set(that.list[idx], 'rateState', false);
								// that.$set(that.list[idx], 'progress', 100);
							}
						});
					} else {
						console.log('取消下载');
					}
				}
			});
		},
		openLook(val, idx) {
			// let that = this;
			uni.showLoading({
				title: '正在打开资料……'
			});
			uni.getSystemInfo({
				success: res => {
					// PC端视频和图片预览
					if (res.platform == 'windows' || res.platform == 'mac' || res.platform == 'devtools') {
						uni.hideLoading();
						if (val.file_type == 'mp4' || val.file_type == 'mp3') {
							this.fileShow = true;
							this.fileSrc = val.img_url;
							this.$set(this.list[idx], 'fileShow', true);
						} else if (
							val.file_type == 'jpg' ||
							val.file_type == 'png' ||
							val.file_type == 'gif' ||
							val.file_type == 'psd' ||
							val.file_type == 'tif' ||
							val.file_type == 'bmp' ||
							val.file_type == 'webp'
						) {
							uni.previewImage({
								urls: [val.route_url || val.img_url],
								success: data => {
									return;
								},
								fail: err => {
									console.log(err.errMsg);
								}
							});
						} else {
							this.openFile(val.route_url || val.img_url, idx);
						}
						return;
					}
					this.openFile(val.route_url || val.img_url, idx);
				}
			});
		},
		openFile(val, idx) {
			// 移动端可查看全部文件
			uni.openDocument({
				//新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
				filePath: val,
				showMenu: true,
				complete: () => {
					uni.hideLoading();
				},
				success: res => {
					console.log('打开文档成功');
				},
				fail: err => {
					console.log(err);
					this.$set(this.list[idx], 'route_url', ''); //防止文件下载后手动更改路径，导致文件打开失败，所以需要再次下载
					setTimeout(() => {
						uni.$u.toast('请下载后查看~');
					}, 1000);
				}
			});
		},
		closePopup(val, idx) {
			this.$set(this.list[idx], 'fileShow', false);
		},
		// 前往现场通讯录
		toCardlist() {
			let zhMsg = uni.getStorageSync('exhibition');
			if (zhMsg.exhibitionId == 0) {
				// 跳转展会列表
				this.goPages('/subPages/exhibition/list');
			} else {
				// 跳转展会详情
				// if (zhMsg.state == 1) {
				// 	this.goPages('/subPages/exhibition/before?id=' + zhMsg.exhibitionId + '&active=' + zhMsg.state);
				// } else {
				uni.setStorageSync('productType', 'qz');
				uni.setStorageSync('mycodeSuccess', zhMsg.exhibitionId);
				this.goPages('/subPages/exhibition/index?id=' + zhMsg.exhibitionId + '&active=' + zhMsg.state);
				// }
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.tit {
	table-layout: fixed;
	word-wrap: break-word;
	word-break: normal;
	overflow: hidden;
}

.imgicon {
	width: 48rpx;
	height: 52rpx;
}

::v-deep .u-popup__content {
	background: transparent !important;
}

.over_box {
	image {
		height: 730rpx;
		position: relative;
	}

	.top_text {
		position: absolute;
		top: 30rpx;
		left: 50%;
		margin-left: -158rpx;
	}

	.over_cont {
		top: 322rpx;
		margin-left: -170rpx;

		.bot_btn {
			button {
				border-radius: 75rpx;
			}
		}
	}
}
</style>
